Page({
  data: {
    detailData: {},
    count: 1,
    userId: wx.getStorageSync('userid') || '', 
    token: wx.getStorageSync('token') || ''
  },

  onLoad(options) {
    const proid = options.proid;
    this.setData({
      userId: wx.getStorageSync('userid') || '', 
      token: wx.getStorageSync('token') || ''
    });
    wx.request({
      url: `http://47.94.6.186:3001/api/pro/detail/${proid}`, 
      method: 'GET',
      success: res => this.setData({ detailData: res.data.data }),
      fail: err => console.log(err)
    });
  },

  addCount() {
    this.setData({ count: this.data.count + 1 });
  },

  minusCount() {
    if (this.data.count > 1) {
      this.setData({ count: this.data.count - 1 });
    }
  },

  goToCart() {
    wx.switchTab({ url: '/pages/cart/cart' });
  },

  addToCart() {
    const { proid } = this.data.detailData;
    const { count, userId, token } = this.data;

    if (!proid) {
      wx.showToast({ title: '商品信息加载中', icon: 'none' });
      return;
    }
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    if (count <= 0) {
      wx.showToast({ title: '请选择商品数量', icon: 'none' });
      return;
    }

    wx.request({
      url: 'http://47.94.6.186:3001/api/cart/add',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': token
      },
      data: { userid: userId, proid, num: count },
      success: res => {
        if (res.data.code === '200' || res.data.message === '加入购物车成功') {
          wx.showToast({ title: '加入购物车成功', icon: 'success' });
        } else {
          wx.showToast({ title: res.data.message || '加入购物车失败', icon: 'none' });
        }
      },
      fail: err => {
        console.error('加入购物车请求失败:', err);
        wx.showToast({ title: '网络异常，加入购物车失败', icon: 'none' });
      }
    });
  }
});